using System;
using Microsoft.Xna.Framework;

namespace SpriteAnimations.Graphics.Animations
{
    class PathAnimation : SpriteAnimation
    {
        //
        // Fields
        //
        private float velocityPerSecond;
        private Vector2[] waypoints;
        private int currentWaypoint = 0;

        //
        // Constructors
        //
        public PathAnimation(float velocityPerSecond, params Vector2[] waypoints)
        {
            this.velocityPerSecond = velocityPerSecond;
            this.waypoints = waypoints;
        }

        //
        // Virtual Methods
        //
        public override void Animate(TimeSpan gameTime, SpriteParameters animatedParameters)
        {
            // This offset is how much we need to move based on how much time 
            // has elapsed.
            float maxDistance = (float)gameTime.TotalSeconds * velocityPerSecond;

            // The vector that is left to get to the current waypoint
            Vector2 remainingVector = waypoints[currentWaypoint] - base.AnimatedSprite.Parameters.Position;
            if (remainingVector.Length() > maxDistance)
            {
                // The vector is longer than we can travel,
                // so limit to our maximum travel distance
                remainingVector.Normalize();
                remainingVector *= maxDistance;
            }

            // Move
            base.AnimatedSprite.Parameters.Position += remainingVector;
            animatedParameters.Position += remainingVector;

            // Are we finished?
            if (WaypointHasBeenReached())
            {
                if (OnLastWaypoint())
                {
                    // No more waypoints, so this animation is finished
                    base.IsFinished = true;
                }
                else
                {
                    // We have more waypoints to go. NEXT!
                    currentWaypoint++;
                }
            }
        }

        //
        // Private Methods
        //
        private bool OnLastWaypoint()
        {
            return (currentWaypoint == waypoints.Length - 1);
        }

        private bool WaypointHasBeenReached()
        {
            return (base.AnimatedSprite.Parameters.Position == waypoints[currentWaypoint]);
        }
    }
}
